package com.jiyun.jiyunmall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiyun.jiyunmall.common.dto.auth.MemberDTO;
import com.jiyun.jiyunmall.common.service.impl.CrudServiceImpl;
import com.jiyun.jiyunmall.member.dao.MemberDao;
import com.jiyun.jiyunmall.member.dao.MemberLevelDao;
import com.jiyun.jiyunmall.member.dto.SocialUser;
import com.jiyun.jiyunmall.member.entity.MemberEntity;
import com.jiyun.jiyunmall.member.entity.MemberLevelEntity;
import com.jiyun.jiyunmall.member.exception.PhoneExistException;
import com.jiyun.jiyunmall.member.exception.UserNameExistException;
import com.jiyun.jiyunmall.member.service.MemberService;
import com.jiyun.jiyunmall.member.util.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 会员
 *
 * @author boge 71164376@qq.com
 * @since 1.0.0 2022-07-12
 */
@Service
public class MemberServiceImpl extends CrudServiceImpl<MemberDao, MemberEntity, MemberDTO> implements MemberService {

    @Override
    public QueryWrapper<MemberEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }


        /*
               用户名：不能重复
               密码：加密，安全度要进行认证，123123
               手机号：不能重复
         */
        @Autowired
        MemberDao memberDao;
         @Autowired
    MemberLevelDao memberLevelDao;
    /**
     * 注册会员
     */
    @Override
    public void regist(MemberDTO memberDTO) {
        MemberEntity entity = new MemberEntity();
        // 1、设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        // 2、 检查用户名和手机号是否唯一，为了让Controller感知异常，我们采用异常机制
        checkPhoneUnique(memberDTO.getMobile());
        checkUserNameUnique(memberDTO.getUsername());
        // 唯一之后执行
        entity.setMobile(memberDTO.getMobile());
        entity.setUsername(memberDTO.getUsername());

        // 3、密码要进行加密存储
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(memberDTO.getPassword());
        entity.setPassword(encode);
        // 保存
        memberDao.insert(entity);
    }

    @Override
    public MemberEntity login(MemberDTO memberDTO) {
        String username = memberDTO.getUsername();
        String password = memberDTO.getPassword();
        // 只要手机号和密码任何一个匹配都查出来
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", username).or().eq("mobile", password));
        if (entity == null) {
            // 登录失败
            return null;
        } else {
            // 2、获取到数据库的password
            String passworDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            // 3、密码匹配
            boolean matches = passwordEncoder.matches(password, passworDb);
            if (matches) {
                return entity;
            }else {
                return null;
            }
        }
    }

    /**
     * 社交登录方法，主要逻辑：
     *  1、先查询一下，该用户是否已经注册
     *     已注册：更新一下accessToken
     *     未注册：根据accessToken，去微博Oauth服务器中，获取用户的各种信息，比如昵称、头像，然后保存到自己的数据库中
     *
     *
     * @param socialUser
     * @return
     * @throws Exception
     */
    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {

        //具有登录和注册逻辑
        String uid = socialUser.getUid();

        //1、判断当前社交用户是否已经登录过系统
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));

        if (memberEntity != null) {
            //这个用户已经注册过
            //更新用户的访问令牌的时间和access_token
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            memberDao.updateById(update);

            // 返回一个member会员信息，会员信息中的AccessToken、ExpiresIn都更新一下
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        } else {
            //2、没有查到当前社交用户对应的记录我们就需要注册一个
            MemberEntity register = new MemberEntity();
            //3、查询当前社交用户的社交账号信息（昵称、性别等），拿着accessToken去问微博的OAuth服务端去获取
            Map<String,String> query = new HashMap<>();
            query.put("access_token",socialUser.getAccess_token());
            query.put("uid",socialUser.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);

            if (response.getStatusLine().getStatusCode() == 200) {
                //查询成功
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String name = jsonObject.getString("name");
                String gender = jsonObject.getString("gender");
                String profileImageUrl = jsonObject.getString("profile_image_url");
                // 。。。。获取一些其他的用户信息
                register.setNickname(name);
                register.setGender("m".equals(gender)?1:0);
                register.setHeader(profileImageUrl);
                register.setCreateTime(new Date());
                register.setSocialUid(socialUser.getUid());
                register.setAccessToken(socialUser.getAccess_token());
                register.setExpiresIn(socialUser.getExpires_in());

                //把用户信息插入到数据库中
                memberDao.insert(register);

            }
            return register;
        }

    }

    /**
     * 校验手机号是否存在
     * @param phone
     */
    private void checkPhoneUnique(String phone) throws PhoneExistException {
        /*
        查询手机号是否存在
            select count(*) from 会员表 where phone字段=#{手机号值}
         */
        Long mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(mobile > 0){
            // 说明手机号是存在的
            throw new PhoneExistException();
        }
    }

    /**
     * 校验账号是否存在
     * @param userName
     */
    private void checkUserNameUnique(String userName) throws UserNameExistException {
        Long username = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if(username > 0){
            throw new UserNameExistException();
        }
    }
}